package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.queryObject.StrategyCatalogQueryObject;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.vo.StrategyCatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired IDestinationService destinationService;
    @Autowired
    private IStrategyService strategyService;

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        // 以防万一把要保存的对象的id设置为空
        strategyCatalog.setId(null);
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepository.deleteById(id);
    }

    @Override
    public StrategyCatalog get(String id) {
        Optional<StrategyCatalog> strategyCatalog = strategyCatalogRepository.findById(id);
        return strategyCatalog.orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {
        List<StrategyCatalog> all = strategyCatalogRepository.findAll();
        return all;
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQueryObject qo) {

        // 封装查询条件
        Query query = new Query();

        // 总条数
        long totalCount = template.count(query, StrategyCatalog.class);

        // 如果总条数为0 , 那么返回空的分页对象
        if (totalCount==0){
            return Page.empty();
        }

        // 分页对象 , 参数1为当前页 从0开始 , 参数2为每页显示条数 , 参数3为排序方式, 参数4为按哪个字段排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                Sort.Direction.ASC,"id");

        query.with(pageable);// 添加查询条件

        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);

        // PageImpl 为 Page 接口的一个实现类
        return new PageImpl<>(list, pageable,totalCount );

    }

    @Override
    public List<StrategyCatalogVO> queryCatalogs() {

        // 先创建一个空的list
        List<StrategyCatalogVO> list = new ArrayList<>();

        TypedAggregation<StrategyCatalog> aggregation = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName")
                        .push("name").as("names")
                        .push("id").as("ids")
        );
        /*
        相当于mongdb里的聚合查询
        db.strategy_catalog.aggregate([{
            $group:{
                _id:"destName",
                names:{
                    $push:"$name"
                },
                ids:{
                    $push:"$_id"
                }
            }
        }])
        */
        // 查询结果
        AggregationResults<Map> results = template.aggregate(aggregation, Map.class);
        // 把查询结果转换成一个list
        List<Map> mappedResults = results.getMappedResults();

        for (Map mappedResult : mappedResults) {// 遍历查询结果
            // 创建一个 StrategyCatalogVO 对象
            StrategyCatalogVO vo = new StrategyCatalogVO();

            vo.setDestName(mappedResult.get("_id").toString());  //id
            List<Object> names = (List<Object>) mappedResult.get("names");  //攻略分类的名称集合
            List<Object> ids = (List<Object>) mappedResult.get("ids");  //攻略分类的ids集合

            List<StrategyCatalog> catalogList = new ArrayList<>(); //攻略分类对象

            for(int i = 0;i < names.size(); i++){
                StrategyCatalog sc = new StrategyCatalog();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                sc.setId(id);
                sc.setName(name);
                catalogList.add(sc);
            }
            vo.setCatalogs(catalogList);
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<StrategyCatalog> queryCatalogsByDestId(String destId) {

        List<StrategyCatalog> list = strategyCatalogRepository.findByDestId(destId);

        for (StrategyCatalog strategyCatalog : list) {
            List<Strategy> lits1 = strategyService.queryStrategiesByCatalogId(strategyCatalog.getId());
            strategyCatalog.setStrategies(lits1);
        }


        return list;
    }



}
